package com.cxf.windex.biz;

import com.cxf.windex.base.bean.LockInfo;
import com.cxf.windex.base.biz.BaseBiz;
import com.cxf.windex.base.common.ServiceException;
import com.cxf.windex.base.constant.LockConstant;
import com.cxf.windex.base.constant.UserConstant;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.entity.Activity;
import com.cxf.windex.entity.Money;
import com.cxf.windex.entity.MoneyLog;
import com.cxf.windex.enums.OperateEnum;
import com.cxf.windex.mapper.MoneyLogMapper;
import com.cxf.windex.task.LogTask;
import com.github.pagehelper.PageHelper;

import java.math.BigDecimal;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * @program: business_needs
 * @description: 资金记录业务
 * @author: chenxf
 * @create: 2018-10-29 09:36
 **/
@Service
public class MoneyLogBiz extends BaseBiz<MoneyLogMapper,MoneyLog> {
  @Autowired
  private MoneyBiz moneyBiz;
  @Autowired
  private LogTask logTask;
  /**
   * 资金记录列表
   *
   * @param limit 数量
   * @param offset 页码
   * @param orderStr  排序(升序或者降序)
   * @param status  状态 0未发布 1进行中
   * @param wxopenid 微信 openid
   * @param operateType  操作类型
   * @return
   */
  public List<MoneyLog> list(int limit, int offset,  String orderStr,String status,String wxopenid,String operateType) {
    Example example = new Example(MoneyLog.class);
    Example.Criteria criteria = example.createCriteria()
        ;
    if(StringUtils.isNotBlank(operateType)){
      criteria.andLike("type",  "%"+operateType+"%" );
    }
    if(StringUtils.isNotBlank(wxopenid)){
      criteria.andLike("wxopenid",  wxopenid );
    }
    if(StringUtils.isNotBlank(status)){
      criteria .andEqualTo("status", status);
    }
    example.setOrderByClause("crt_time " + orderStr);
    PageHelper.startPage(offset, limit);
    return selectByExample(example);
  }

  /**
   * 保存活动
   * @param entity
   */
  public void save(MoneyLog entity){
    if(entity.getId()==null|| StringUtils.isBlank(entity.getId())){
      entity.setId(UserConstant.LOG_ID_PREX+new IdUtil(5,1).nextId());
      insertSelective(entity);
    }else{
      updateSelectiveById(entity);
    }
  }

  /**
   * 提现成功
   * @param zcCount 提现金额
   * @param notes 提现备注
   * @param id 提现ID
   */
  public void cashSuc(String notes,String zcCount, String id) {
    if (StringUtils.isBlank(zcCount)) {
      throw new ServiceException("提现金额不能为空");
    }
    if (StringUtils.isBlank(id)) {
      throw new ServiceException("提现ID不能为空");
    }
    MoneyLog log = selectById(id);

    String userId = log.getWxopenid();
    //账号转入
    LockInfo lockInfo = new LockInfo(LockConstant.USER_LOCK + userId);
    try {
      Money money = moneyBiz.selectOne(Money.builder().wxopenid(userId).build());
      if (money == null) {
        lockInfo.unlock();
        throw new ServiceException("用户资金信息查询失败");
      }
      if (money.getWithdraw().compareTo(new BigDecimal(zcCount)) < 0) {
        lockInfo.unlock();
        throw new ServiceException("提现冻结钱包余额不足");
      }

      money.setWithdraw(money.getWithdraw().subtract(new BigDecimal(zcCount)));
      logTask.doQbzz(money, OperateEnum.INCOME_CASH_S,
              notes, zcCount,null,id);

    } catch (Throwable throwable) {
      throwable.printStackTrace();
      lockInfo.unlock();
      throw new ServiceException(throwable.getMessage());
    } finally {
      lockInfo.unlock();
    }
    log.setStatus("1");
    this.updateSelectiveById(log);
  }

  /**
   * 提现退回
   * @param notes
   * @param id
   */
  public void cashFail(String notes, String id) {
    if (StringUtils.isBlank(id)) {
      throw new ServiceException("提现ID不能为空");
    }
    MoneyLog log = this.selectById(id);

    String userId = log.getWxopenid();
    //账号转入
    LockInfo lockInfo = new LockInfo(LockConstant.USER_LOCK + userId);
    try {
      Money money = moneyBiz.selectOne(Money.builder().wxopenid(userId).build());
      if (money == null) {
        lockInfo.unlock();
        throw new ServiceException("用户资金信息查询失败");
      }
      if (money.getWithdraw().compareTo(log.getMoney()) < 0) {
        lockInfo.unlock();
        throw new ServiceException("提现冻结余额不足");
      }
      money.setWithdraw(money.getWithdraw().subtract(log.getMoney().abs()));
      money.setIncome(money.getIncome().add(log.getMoney().abs()));
      logTask.doQbzz(money, OperateEnum.INCOME_CASH_F, notes, log.getMoney().abs().toString(),null,id);

    } catch (Throwable throwable) {
      lockInfo.unlock();
      throw new ServiceException(throwable.getMessage());
    } finally {
      lockInfo.unlock();
    }
    //设置提现为已处理
    log.setStatus("3");
    this.updateSelectiveById(log);
  }
}
